package com.wan.net.rpc;

import com.wan.net.config.HostAndPort;
import com.wan.net.core.AbstractServer;
import com.wan.net.core.ServerType;
import com.wan.net.core.tcp.TcpCodec;
import com.wan.net.rpc.service.RpcService;
import com.wan.net.rpc.util.RpcConstants;
import io.netty.channel.ChannelPipeline;

import java.util.HashSet;
import java.util.Set;


/**
 * @author wwh
 * @date 2022/6/17 10:43
 */
public class RpcServer extends AbstractServer {
    public static final String DEFAULT_NAME = "default";

    private final String name;
    /** server对应的服务（包含地址等信息）*/
    private final RpcService rpcService;
    /** 所有子服务提供 */
    private final Set<RpcService> subServices = new HashSet<>();

    public RpcServer(HostAndPort hostAndPort){
        this(hostAndPort,DEFAULT_NAME);
    }

    public RpcServer(HostAndPort hostAndPort, String name) {
        super(hostAndPort, RpcConstants.IDLE_TIMEOUT);
        this.name = name;
        this.rpcService = RpcService.create().hostAndPort(hostAndPort);
    }

    @Override
    protected void channelChannelInitializer(ChannelPipeline pipeline) {
        pipeline.addLast(new TcpCodec());
    }

    @Override
    public synchronized void start() {
        super.start();
        RpcManager.addRpcServer(this);
    }

    @Override
    public ServerType getServerType() {
        return ServerType.RPC;
    }

    public String getName() {
        return name;
    }

    /**
     * 添加额外参数，只能在启动前调用
     */
    public void addParam(String name,Object value){
        if(startStatus.get()){
            return;
        }
        this.rpcService.addParam(name,value);
    }

    public RpcService getRpcService(){
        return this.rpcService;
    }

    public void addSubService(RpcService rpcService){
        this.subServices.add(rpcService);
    }

    @Override
    public synchronized void shutdown() {
        for (RpcService subService : this.subServices) {
            RpcManager.getRegistry().unregister(subService);
        }
        super.shutdown();
    }
}
